package com.example.smartgreenhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smartgreenhouse.entity.PumpOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.mapper.PumpOperationLogMapper;
import com.example.smartgreenhouse.mqtt.MqttMessageSender;
import com.example.smartgreenhouse.service.PumpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PumpServiceImpl implements PumpService {

    private final PumpOperationLogMapper pumpOperationLogMapper;
    @Autowired
    private MqttMessageSender mqttMessageSender;

//    @Autowired
//    private ThresholdServiceImpl thresholdService;

    @Value("${mqtt.topic.water_pump_cmd}")
    private String topic_water_pump_cmd;

    @Value("${mqtt.topic.water_pump_auto_cmd}")
    private String topic_water_pump_auto_cmd;

    //这里没有写入Mysql中。
    //cation == 1 开启自动控制
    //cation == 0 关闭自动控制
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> setPumpAuto(Long pumpId, Long greenhouseId, Long operatorId, Integer action) {
        try {
            mqttMessageSender.publish(topic_water_pump_auto_cmd, String.valueOf(action));
            log.info("已发送水泵控制指令: pumpId={}, is_auto={}", pumpId, action == 1);
        } catch (Exception e) {
            log.error("MQTT发布失败 | Topic: device/pump/{}/control | 错误: {}", pumpId, e.getMessage());
            throw new RuntimeException("水泵控制指令发送失败，请检查MQTT连接配置", e); // 明确提示检查配置
//            log.error("水泵控制指令发送失败", e);
//            throw new RuntimeException("水泵控制指令发送失败");
        }
        Map<String,Object> operationLog = new HashMap<>();
        operationLog.put("code",200);
        operationLog.put("status","success");
        if(action==1){
            operationLog.put("message","水泵自动控制开启");
        }else{
            operationLog.put("message","水泵自动控制关闭");
        }
        operationLog.put("operationTime",LocalDateTime.now());
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PumpOperationLog controlPump(Long pumpId, Long greenhouseId, String level, Long operator) {

        // 校验ENUM值
        if (!Arrays.asList("0", "1", "2", "3").contains(level)) {
            throw new BusinessException("档位必须是'0','1','2','3'");
        }

        // 发送控制指令
        sendControlCommand(pumpId, level);

        // 记录操作日志
        return recordOperation(pumpId, greenhouseId, level, operator);
    }

    @Override
    public List<PumpOperationLog> getPumpHistory(Long pumpId) {
        return pumpOperationLogMapper.selectList(
                new LambdaQueryWrapper<PumpOperationLog>()
                        .eq(PumpOperationLog::getPumpId, pumpId)
                        .orderByDesc(PumpOperationLog::getOperateTime)
        );
    }

    @Override
    public PumpOperationLog getCurrentStatus(Long pumpId) {
        return pumpOperationLogMapper.selectOne(
                new LambdaQueryWrapper<PumpOperationLog>()
                        .eq(PumpOperationLog::getPumpId, pumpId)
                        .orderByDesc(PumpOperationLog::getOperateTime)
                        .last("LIMIT 1")
        );
    }
    private void sendControlCommand(Long pumpId, String level) {
        try {
            //String topic = String.format("device/pump/%d/control", pumpId);
            //String topic = "water_pump_cmd";
            mqttMessageSender.publish(topic_water_pump_cmd, String.valueOf(level));
            log.info("已发送水泵控制指令: pumpId={}, level={}", pumpId, level);
        } catch (Exception e) {
            log.error("MQTT发布失败 | Topic: device/pump/{}/control | 错误: {}", pumpId, e.getMessage());
            throw new RuntimeException("水泵控制指令发送失败，请检查MQTT连接配置", e); // 明确提示检查配置
//            log.error("水泵控制指令发送失败", e);
//            throw new RuntimeException("水泵控制指令发送失败");
        }
    }

    private PumpOperationLog recordOperation(Long pumpId, Long greenhouseId,
                                             String level, Long operatorId) {
        PumpOperationLog log = new PumpOperationLog();
        log.setPumpId(pumpId);
        log.setGreenhouseId(greenhouseId);
        log.setOperatorId(operatorId);
        log.setOperateTime(LocalDateTime.now());
        log.setLevel(level);
        pumpOperationLogMapper.insert(log);
        return log;
    }
}